package com.one.rope.mvp.basecore.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @author Weijian.liu
 * @desc IP工具类
 * @date 2018/12/21
 */
public class IpUtils {

  private static final String LOCALIP = "0:0:0:0:0:0:0:1";

  public static String getIp(HttpServletRequest request) {
    try {
      String ipAddress = request.getRemoteAddr();
      if (LOCALIP.equals(ipAddress)) {
        InetAddress localip = InetAddress.getLocalHost();
        ipAddress = localip.getHostAddress();
      }
      return StringUtils.isNullSetEmpty(ipAddress);
    } catch (Exception e) {
      return "";
    }
  }

  public static String getForwardedIp(HttpServletRequest request) {
    String forwardedIp = request.getHeader("X-FORWARDED-FOR");
    return StringUtils.isNullSetEmpty(forwardedIp);
  }

  public static String getClientIp(HttpServletRequest request) {
    return "".equals(getForwardedIp(request)) ? getIp(request) : getForwardedIp(request);
  }

}
